package com.jky.trial.controller;

import com.jky.trial.annotation.NoRepeatSubmit;
import com.jky.trial.common.BaseResult;
import com.jky.trial.common.DateUtil;
import com.jky.trial.common.ListResult;
import com.jky.trial.common.jwt.JWTUtil;
import com.jky.trial.constant.DataConstant;
import com.jky.trial.constant.DataStatus;
import com.jky.trial.constant.PermissionConstant;
import com.jky.trial.entity.Category;
import com.jky.trial.entity.User;
import com.jky.trial.service.*;
import com.jky.trial.vo.CategoryVo;
import com.jky.trial.vo.ProjectVo;
import com.jky.trial.vo.RecordVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/v1/category")
public class CategoryController {

    private ProjectService projectService;
    private CategoryService categoryService;
    private RecordService recordService;
    private TaskSampleService taskSampleService;
    private UserService userService;

    @Autowired
    CategoryController(
            ProjectService projectService,
            RecordService recordService,
            UserService userService,
            CategoryService categoryService, TaskSampleService taskSampleService) {
        this.taskSampleService = taskSampleService;
        this.projectService = projectService;
        this.recordService = recordService;
        this.userService = userService;
        this.categoryService = categoryService;
    }

    @PostMapping
    @NoRepeatSubmit
    public BaseResult create(@RequestBody Category record, HttpServletRequest request) {
        User user = JWTUtil.getUser(request.getHeader("tk"));
        return categoryService.create(record, user);
    }

    @PostMapping("/test")
    @NoRepeatSubmit
    public BaseResult createTest(HttpServletRequest request) {
        System.out.println("test");
        return new BaseResult(true, "");
    }

    /**
     * 上传任务书
     *
     * @param record
     * @param request
     * @return
     */
    @PostMapping("/uploadReport")
    public BaseResult uploadReport(@RequestBody Category record, HttpServletRequest request) {
        User user = JWTUtil.getUser(request.getHeader("tk"));
        return categoryService.uploadReport(record, user);
    }

    @PutMapping
    public BaseResult update(@RequestBody Category record) {
        return new BaseResult(true, categoryService.update(record));
    }

    /**
     * 提交确认单至试验室
     *
     * @param record
     * @return
     */
    @PutMapping("/submitBill")
    public BaseResult check(@RequestBody Category record, HttpServletRequest request) {
        User user = JWTUtil.getUser(request.getHeader("tk"));
        return categoryService.submitBill(record, user);
    }

    /**
     * 设置土样时，所需数据汇总接口
     *
     * @param id
     * @return
     */
    @GetMapping("/sampleDetailSum/{id}")
    public BaseResult sampleDetail(@PathVariable Integer id) {
        Map<String, Object> res = new HashMap<String, Object>();
        res.put("book", taskSampleService.bookSamplev2(id));
        Category category = categoryService.detail(id);
        res.put("category", category);
        CategoryVo categoryVo = new CategoryVo();
        categoryVo.setName(PermissionConstant.TASK_BOOK_CHECK);
        res.put("checkers", userService.listByPermission(categoryVo));
        RecordVo recordVo = new RecordVo();
        recordVo.setType(DataStatus.LOG_SUB_TYPE_RECORD_SHUIWEI.getVal());
        recordVo.setProjectId(category.getPId());
        recordVo.setDeleted(false);
        List<RecordVo> list = recordService.list(recordVo);
        res.put("shuiwei", list);
        return new BaseResult(true, res);
    }

    /**
     * 提交任务书
     *
     * @param record
     * @param request
     * @return
     */
    @PutMapping("/submitBook")
    public BaseResult submitBook(@RequestBody Category record, HttpServletRequest request) {
        User user = JWTUtil.getUser(request.getHeader("tk"));
        if (PermissionConstant.ADMIN_USER.equals(user.getId())) {
            return new BaseResult(false, "超级管理员账号不能参与业务管理");
        }
        return categoryService.submitBook(record, user);
    }

    /**
     * 审核任务书
     *
     * @param record
     * @param request
     * @return
     */
    @PutMapping("/checkBook")
    public BaseResult checkBook(@RequestBody Category record, HttpServletRequest request) {
        User user = JWTUtil.getUser(request.getHeader("tk"));
        return categoryService.checkBook(record, user);
    }

    /**
     * 发布试验成果报告
     *
     * @param record
     * @param request
     * @return
     */
    @PutMapping("/submitReport")
    public BaseResult submitReport(@RequestBody Category record, HttpServletRequest request) {
        User user = JWTUtil.getUser(request.getHeader("tk"));
        return new BaseResult(true, categoryService.publishReport(record, user));
    }

    @DeleteMapping("/{id}")
    public BaseResult del(@PathVariable Integer id) {
        Category category = categoryService.detail(id);
        if (category.getType().equals(DataStatus.CATEGORY_DATA_TYPE_ROLE.getVal())) {
            if (id == 39) return new BaseResult(false, "管理员角色不能删除");
        }
        if (category.getDeleted()) return new BaseResult(false, "该数据已删除，不能重复操作");
        Subject subject = SecurityUtils.getSubject();
        //删除角色权限
        if (DataStatus.CATEGORY_DATA_TYPE_ROLE.getVal()
                .equals(category.getType()) &&
                !subject.isPermitted(PermissionConstant.DELETE_ROLE)) {
            return new BaseResult(false, DataConstant.NO_AUTH.toString(), 401);
        }
        //删除勘察、委托、施工单位联系人权限
        if (DataStatus.CATEGORY_DATA_TYPE_PERSON.getVal()
                .equals(category.getType()) &&
                !subject.isPermitted(PermissionConstant.DELETE_CATEGORY_PERSON)) {
            return new BaseResult(false, DataConstant.NO_AUTH.toString(), 401);
        }
        //删除勘察单位、委托单位、施工单位权限
        if ((DataStatus.CATEGORY_DATA_TYPE_COM1.getVal()
                .equals(category.getType()) || DataStatus.CATEGORY_DATA_TYPE_COM2.getVal()
                .equals(category.getType()) || DataStatus.CATEGORY_DATA_TYPE_COM3.getVal()
                .equals(category.getType())) &&
                !subject.isPermitted(PermissionConstant.DELETE_CATEGORY_COM)) {
            return new BaseResult(false, DataConstant.NO_AUTH.toString(), 401);
        }
        //删除部门权限
        if (DataStatus.CATEGORY_DATA_TYPE_DEP.getVal()
                .equals(category.getType()) && !subject.isPermitted(PermissionConstant.DELETE_DEP)) {
            return new BaseResult(false, DataConstant.NO_AUTH.toString(), 401);
        }
        //删除业务板块权限
        if (DataStatus.CATEGORY_DATA_TYPE_BUS.getVal()
                .equals(category.getType()) && !subject.isPermitted(PermissionConstant.DELETE_BUS)) {
            return new BaseResult(false, DataConstant.NO_AUTH.toString(), 401);
        }
        return new BaseResult(true, categoryService.del(id));
    }

    @GetMapping("/{id}")
    public BaseResult get(@PathVariable Integer id) {
        return new BaseResult(true, categoryService.detail(id));
    }

    /**
     * 确认单详情，包含提交人
     *
     * @param id
     * @return
     */
    @GetMapping("/bill/{id}")
    public BaseResult billDetail(@PathVariable Integer id) {
        return new BaseResult(true, categoryService.billDetail(id));
    }


    @GetMapping("/detail/{id}")
    public BaseResult detail(@PathVariable Integer id) {
        return new BaseResult(true, categoryService.detail(id));
    }


    @GetMapping
    public ListResult page(CategoryVo record) {
        return categoryService.page(record);
    }

    /**
     * 业务单位 pageWithPerson
     *
     * @param record
     * @return
     */
    @GetMapping("/pageWithPerson")
    public ListResult pageWithPerson(CategoryVo record) {
        return categoryService.pageWithPerson(record);
    }

    /**
     * 钻机
     *
     * @param record
     * @return
     */
    @GetMapping("/pageZj")
    public ListResult pageZj(CategoryVo record) {
        return categoryService.zjList(record);
    }

    /**
     * record.type category类型
     * record.page 页码
     * record.size 每页数量
     *
     * @param record
     * @return
     */
    @GetMapping("/withProject")
    public ListResult pageWithProject(CategoryVo record) {


        return categoryService.pageWithProject(record);
    }

    /**
     * 根据授权情况查看用户权限范围内项目
     *
     * @param record
     * @return
     */
    @GetMapping("/withProjectByPermission")
    public ListResult withProjectByPermission(CategoryVo record, HttpServletRequest request) {
        User user = JWTUtil.getUser(request.getHeader("tk"));
        return categoryService.withProjectByPermission(record, user);
    }


    @GetMapping("/list")
    public ListResult list(CategoryVo record) {
        return new ListResult(true, categoryService.list(record));
    }

    /**
     * 土分析试验委托书
     *
     * @param record
     * @return
     */
    @GetMapping("/exportTaskBook")
    public OutputStream exportTaskBook(CategoryVo record, HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        record = categoryService.moreDetail(record.getId());
        String fileName = URLEncoder.encode(record.getProjectName() + "土分析委托书-" + DateUtil.dateToStr(new Date()), "UTF-8");
        response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xls");// 组装附件名称和格式
        response.setCharacterEncoding("UTF-8");
        ProjectVo projectVo = projectService.moreDetail(record.getComId());

        return categoryService.exportExcel(record, response.getOutputStream(), projectVo.getDutyName());
    }

}
